<template>
  <div class="app-container">
    <el-dialog title="题目详情" @open="getExamQu" class="exam-qu-show-dialog" :visible.sync="options.examQuShowDialog" width="50%">
      <el-card class="exam-questions" v-for="(question, quIndex) in examQuList" :key="quIndex">
        <div slot="header">
          <span style="display: inline-block; width: 90%">{{ question.question }}</span>
          <el-button style="float: right; padding: 2px 0" type="text">{{ question.score + '分' }}</el-button>
        </div>
        <div class="choice" v-if="question.type === 'choice'">
          <p style="cursor: pointer" v-for="(item, index) in question.choose" :key="index" @click="question.userAnswer = item">{{ item }}</p>
          <p>{{ '回答：' + question.userAnswer }}</p>
        </div>
        <div class="gap-filling" v-if="question.type === 'fill'">
          <el-input v-for="(item, index) in question.combination" :key="index" style="margin: 10px 0" v-model="item.userAnswer" placeholder="请输入填空题的答案"></el-input>
        </div>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button @click="examAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="finishExam">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog title="解答详情" @open="getExamQuRecord" class="exam-qu-show-dialog" :visible.sync="options.examQuRecordShowDialog" width="50%">
      <el-card class="exam-questions" v-for="(question, quIndex) in examQuList" :key="quIndex">
        <div slot="header">
          <span style="display: inline-block; width: 90%">{{ question.question }}</span>
          <el-button style="float: right; padding: 2px 0" type="text">{{ '得分：' + question.score }}</el-button>
        </div>
        <div class="choice" v-if="question.type === 'choice'">
          <p style="cursor: pointer" v-for="(item, index) in question.choose" :key="index">{{ item }}</p>
          <p>{{ '答案：' + question.answer }}</p>
          <p>{{ '回答：' + question.userAnswer }}</p>
        </div>
        <div class="gap-filling" v-if="question.type === 'fill'">
          <div v-for="(item, index) in question.combination" :key="index" style="margin: 10px 0">
            <span>{{ '第 ' + (index + 1) + ' 空答案：' + item.answer }}</span>
            <span style="margin-left: 20px">{{ '回答：' + item.userAnswer }}</span>
          </div>
        </div>
      </el-card>
    </el-dialog>

    <div class="filter-container" style="margin-bottom: 20px">
      <slot name="filter-content" />
    </div>

    <el-table v-loading="listLoading" ref="table" :data="dataList.records" :row-key="getRowKeys" :row-style="tableRowStyle" :header-cell-style="tableHeaderColor" fit highlight-current-row @sort-change="tableSortChange" @selection-change="handleSelection">
      <el-table-column v-if="options.multi" :reserve-selection="false" align="center" type="selection" width="55" />

      <slot name="data-columns" />
    </el-table>

    <pagination v-show="dataList.total > 0" :total="dataList.total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getList" />
  </div>
</template>

<script>
import { postData } from '@/api/common'
import Pagination from '@/components/Pagination'
import { post } from '@/utils/request'
import { Message, Loading } from 'element-ui'

export default {
  name: 'WebTable',
  components: { Pagination },
  // 组件入参
  props: {
    options: {
      type: Object,
      default: () => {
        return {
          keyId: 'id',
          add: {
            enable: false,
            permission: '',
            router: {}
          },
          edit: {
            enable: false,
            permission: '',
            router: {}
          },
          delete: {
            enable: false,
            permission: '',
            url: ''
          },
          // 批量操作
          multiActions: [],
          // 列表请求URL
          listUrl: '/api/',
          // 删除请求URL
          deleteUrl: '',
          // 启用禁用
          stateUrl: '',
          // 可批量操作
          multi: false
        }
      }
    },

    // 列表查询参数
    listQuery: {
      type: Object,
      default: () => {
        return {
          current: 1,
          size: 10,
          params: {},
          t: 0
        }
      }
    }
  },
  data() {
    return {
      // 接口数据返回
      dataList: {
        total: 0
      },
      // 数据加载标识
      listLoading: true,
      // 选定和批量操作
      selectedIds: [],
      selectedObjs: [],
      // 显示已中多少项
      selectedLabel: '',
      // 显示批量操作
      multiShow: false,
      // 批量操作的标识
      multiNow: '',
      // 考试试题
      examQuList: []
    }
  },
  watch: {
    // 检测查询变化
    listQuery: {
      handler() {
        this.getList()
      },
      deep: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取选定的key
    getRowKeys(row) {
      if (this.options.keyId != null && this.options.keyId !== '') {
        return row[this.options.keyId]
      }
      return row['id']
    },

    /**
     * 查询数据列表
     */
    getList() {
      this.listLoading = true
      this.listQuery.t = new Date().getTime()
      postData(this.options.listUrl, this.listQuery).then(response => {
        this.dataList = response.data
        this.listLoading = false
      })
    },

    /**
     * 列表多选操作
     * @param val
     */
    handleSelection(val) {
      const ids = []
      val.forEach(row => {
        ids.push(row.id)
      })
      this.selectedObjs = val
      this.selectedIds = ids
      this.multiShow = ids.length > 0
      this.selectedLabel = '已选' + ids.length + '项'
      this.$emit('select-changed', { ids: this.selectedIds, objs: this.selectedObjs })
    },

    tableSortChange(column) {
      this.listQuery.pageNo = 1
      if (column.order === 'descending') {
        this.listQuery.orders = [{ column: column.prop, asc: false }]
      } else {
        this.listQuery.orders = [{ column: column.prop, asc: true }]
      }
      this.getList()
    },

    // 清理选择的
    clearSelection() {
      this.$refs.table.clearSelection()
    },

    // 设置表格行的样式
    tableRowStyle({ row, rowIndex }) {
      return 'background-color:#666;font-size:16px;'
    },
    // 设置表头行的样式
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      return 'background-color:#F7F9FE;color:#192437;font-wight:700;font-size:16px;'
    },

    // 展示题目的 dialog 的打开回调
    async getExamQu() {
      const questionList = await post('/api/temp/exam/qu/list', { examId: this.options.examId }).then(res => {
        return res.data
      })
      this.examQuList = []
      questionList.forEach(item => {
        const question = JSON.parse(item.question)
        if (question.type === 'choice') {
          question.userAnswer = ''
        } else if (question.type === 'fill') {
          question.combination = []
          for (let i = 0; i < question.answer.length; i++) {
            question.combination.push({
              answer: question.answer[i],
              userAnswer: ''
            })
          }
        }
        this.examQuList.push(question)
      })
      console.log(this.examQuList)
    },

    // 展示已回答题目的 dialog 的打开回调
    async getExamQuRecord() {
      const questionList = await post('/api/temp/exam/qu/list/answer', { examId: this.options.examId }).then(res => {
        return res.data
      })
      this.examQuList = []
      questionList.forEach(item => {
        const question = JSON.parse(item.question)
        this.examQuList.push(question)
      })
      console.log(this.examQuList)
    },

    // 提交考试
    finishExam() {
      let flag = false
      this.examQuList.forEach(qu => {
        if (qu.type === 'choice' && qu.userAnswer === '') {
          flag = true
        }
        if (qu.type === 'fill') {
          qu.combination.forEach(item => {
            if (item.userAnswer === '') {
              flag = true
            }
          })
        }
      })
      if (flag) {
        Message({
          message: '还有未答试题',
          type: 'error'
        })
        return
      }
      let loadingInstance = Loading.service({ fullscreen: true, lock: true, text: '请稍后', background: 'rgba(0, 0, 0, 0.7)' })
      this.options.examQuShowDialog = false
      let score = 0
      this.examQuList.forEach(qu => {
        if (qu.type === 'choice') {
          score += qu.userAnswer === qu.answer ? qu.score : 0
          qu.score = qu.userAnswer === qu.answer ? qu.score : 0
        }
        if (qu.type === 'fill') {
          let fillFlag = true
          qu.combination.forEach(item => {
            if (item.userAnswer !== item.answer) {
              fillFlag = false
            }
          })
          if (fillFlag) {
            score += qu.score
          } else {
            qu.score = 0
          }
        }
      })
      const promise01 = post('/api/temp/exam/submit', { examId: this.options.examId, score })
      const promise02 = post('/api/temp/exam/submit/question', { examId: this.options.examId, questionList: this.examQuList })
      // 等待两个请求都完成后执行后续处理
      Promise.all([promise01, promise02])
        .then(([res1, res2]) => {
          if (res1.success && res2.success) {
            Message({
              message: '提交成功',
              type: 'success'
            })
            this.dataList.records.forEach(item => {
              if (item.id === this.options.examId) {
                item.state = '已结束'
              }
            })
          }
        })
        .catch(error => {
          Message({
            message: '提交失败：' + error,
            type: 'error'
          })
        })
      loadingInstance.close()
    }
  }
}
</script>

<style scoped>
::v-deep .filter-container .filter-item {
  margin-left: 10px;
}

::v-deep .filter-container .filter-item:first-child {
  margin-left: 0px;
}

::v-deep .el-table .cell {
  font-size: 14px;
  color: #606266;
}

::v-deep .el-table th.el-table__cell > .cell {
  padding: 10px 5px;
  font-size: 16px;
  color: #192437;
}

.exam-qu-show-dialog {
  height: 90vh;
  top: 5vh;
  scrollbar-width: none !important;
}
::v-deep .exam-qu-show-dialog .el-dialog {
  background-color: #f5f6fa;
}
::v-deep .exam-qu-show-dialog .el-card__body {
  padding: 0 20px !important;
}
.exam-qu-show-dialog .el-card {
  margin-bottom: 20px;
}
</style>
